import Router from '@koa/router';
import jwt from 'jsonwebtoken';
import { BeError, BeSuccess } from '../utils/response';
import log from '../utils/log';
import { GetUserByName } from '../services/systemUser';

const router = new Router();

// 添加用户
router.post('/', async function (ctx) {
  const { userName, password } = ctx.request.body;
  if (!userName || !password) {
    ctx.body = BeError('参数不合法');
    return;
  }

  try {
    const user = await GetUserByName(userName);
    if (!user || user.getDataValue('status') === 0) {
      throw new Error('用户不存在');
    }

    if (password !== user.getDataValue('password')) {
      throw new Error('密码错误');
    }
    const token = jwt.sign({
			name: userName,
			_id: user.getDataValue('id')
		}, 'login_token', { expiresIn: '12h' });
    log.info(`${userName}登录成功`);
    ctx.body = BeSuccess({
      token
    });
  } catch (error) {
    ctx.body = BeError(error.message, 405);
  }
});

export default router.routes();
